import service from '@/utils/request'
import type { AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'

type JsonResult<T> = { code: number; message: string; data: T }

function unwrap<T>(res: AxiosResponse<JsonResult<T>>): T {
  const payload = res.data as any
  if (payload && typeof payload === 'object' && 'code' in payload) {
    if (payload.code === 0) {
      return payload.data as T
    }
    ElMessage.error(payload.message || '接口错误')
    throw new Error(payload.message || '接口错误')
  }
  // 兜底：部分接口可能未被统一包装
  return (res as any).data
}

export async function apiGet<T>(url: string, params?: Record<string, any>): Promise<T> {
  const res = await service.get(url, { params })
  return unwrap<T>(res as any)
}

export async function apiPost<T>(
  url: string,
  data?: any,
  params?: Record<string, any>,
): Promise<T> {
  const res = await service.post(url, data, params ? { params } : undefined)
  return unwrap<T>(res as any)
}

export async function apiPut<T>(url: string, data?: any, params?: Record<string, any>): Promise<T> {
  const res = await service.put(url, data, params ? { params } : undefined)
  return unwrap<T>(res as any)
}

export async function apiDelete<T>(url: string, params?: Record<string, any>): Promise<T> {
  const res = await service.delete(url, params ? { params } : undefined)
  return unwrap<T>(res as any)
}
